from plugin import MSsqlClient, Mylogger
from config import Config


class BaseEntity:
    url = ""  # 接口地址
    table_name = "base"  # 记录库表名
    api_data_list = []  # 从接口获取的数据对象，用于临时存储，定时写入记录库
    create_table = False  # 是否创建表，标志位，创建表后置为false
    get_time = "2000-01-01 00:00:00"  # 上一次从接口取增量数据的时间
    order_by = "id"  # 做同步时的排序字段，防止数据错乱
    sync_list = []  # 同步数据列表
    write_back_dict = {}  # 同步完成后，回写字典 {isdeal: [obj.key]}

    def __init__(self):
        pass

    @classmethod
    def save_to_db(cls):
        client = MSsqlClient(**Config.module_config.huada.record_link)
        if cls.create_table:
            # 获取类的成员变量
            fields = [i for i in cls().__dict__.keys() if not i.startswith('_') and i != "id"]
            client.create_table(cls.table_name, fields, id_increment=True, create_time=True)
            Mylogger.info(f"create table {cls.table_name} success")
            cls.create_table = False
        objs = cls.api_data_list.copy()  # 拷贝一份，防止多线程操作
        Mylogger.info(f"save {len(objs)} records to db {cls.table_name}")
        if client.insert_objects(objs, cls.table_name):
            Mylogger.info(f"save {len(objs)} records to db {cls.table_name} success")
            # 计算差集
            cls.api_data_list = list(set(cls.api_data_list).difference(set(objs)))

    @classmethod
    def append(cls, obj):
        del obj.id  # 中间库自动生成id，不需要id
        # 如果对象里面有系统编码字段，按配置文件中的system_code过滤
        # if hasattr(obj, "dataSysCode") and obj.dataSysCode != Config.module_config.huada.system_code:
        #     return
        cls.api_data_list.append(obj)

    @classmethod
    def append_sync(cls, obj):
        cls.sync_list.append(obj)

    @classmethod
    def do_sync(cls, client: MSsqlClient, objs):
        return True

    @classmethod
    def write_back(cls):
        dic = {}
        # 复制数据
        for k, v in cls.write_back_dict.items():
            dic[k] = v.copy()
        for key, value in dic.items():
            if len(value) > 0:
                client = MSsqlClient(**Config.module_config.huada.record_link)
                # value里面每次取5000条更新
                for i in range(0, len(value), 5000):
                    end = (i + 5000) if len(value) > (i + 5000) else len(value)
                    datas = value[i:end]
                    value_str = "','".join(datas)
                    client.execute(f"update {cls.table_name} set isdeal = {key} where id in ('{value_str}')")
                    Mylogger.info(f"write back {len(datas)} records [{key}] to db {cls.table_name} success")
                    # 处理完成后，去掉处理的数据
                    cls.write_back_dict[key] = list(set(cls.write_back_dict[key]).difference(set(datas)))
        dic.clear()

    # @classmethod
    # def write_back_from_dict(cls, write_back_dict):
    #     dic = {}
    #     # 复制数据
    #     for k, v in write_back_dict.items():
    #         dic[k] = v.copy()
    #     for key, value in dic.items():
    #         if len(value) > 0:
    #             client = MSsqlClient(**Config.module_config.huada.record_link)
    #             # value里面每次取5000条更新
    #             for i in range(0, len(value), 5000):
    #                 end = (i + 5000) if len(value) > (i + 5000) else len(value)
    #                 datas = value[i:end]
    #                 value_str = "','".join(datas)
    #                 client.execute(f"update {cls.table_name} set isdeal = {key} where id in ('{value_str}')")
    #                 Mylogger.info(f"write back {len(datas)} records [{key}] to db {cls.table_name} success")
    #                 # 处理完成后，去掉处理的数据
    #                 write_back_dict[key] = list(set(write_back_dict[key]).difference(set(datas)))
    #     dic.clear()